<template>
  <div class="research-projects">
    <div class="page-header">
      <h1 class="page-title">科研项目管理</h1>
      <div class="header-actions">
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="primary" @click="showFormDialog = true" :icon="Plus">
          新建科研项目
        </el-button>
      </div>
    </div>

    <el-card>
      <!-- 搜索和筛选栏 -->
      <div class="filter-bar">
        <div class="filter-row">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索项目名称"
            style="width: 200px;"
            :prefix-icon="Search"
            clearable
            @input="handleFilterChange"
          />
          <el-select v-model="filterType" placeholder="项目类型" style="width: 110px;" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="纵向" value="纵向" />
            <el-option label="横向" value="横向" />
            <el-option label="校级" value="校级" />
          </el-select>
          <el-select v-model="filterLevel" placeholder="项目级别" style="width: 110px;" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="校级" value="校级" />
            <el-option label="市厅级" value="市厅级" />
            <el-option label="省部级" value="省部级" />
            <el-option label="国家级" value="国家级" />
          </el-select>
          <el-select v-model="filterStatus" placeholder="项目状态" style="width: 120px;" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="申报中" value="申报中" />
            <el-option label="已立项" value="已立项" />
            <el-option label="执行中" value="执行中" />
            <el-option label="结题审核中" value="结题审核中" />
            <el-option label="已结题" value="已结题" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>
          
          <div class="funding-range">
            <span class="filter-label">经费区间：</span>
            <el-input-number
              v-model="filterFundingMin"
              :min="0"
              :precision="2"
              controls-position="right"
              placeholder="最小值"
              style="width: 100px;"
              @change="handleFilterChange"
            />
            <span style="margin: 0 6px;">-</span>
            <el-input-number
              v-model="filterFundingMax"
              :min="0"
              :precision="2"
              controls-position="right"
              placeholder="最大值"
              style="width: 100px;"
              @change="handleFilterChange"
            />
            <span style="margin-left: 4px;">万元</span>
          </div>
          
          <div class="date-range">
            <span class="filter-label">申报时间：</span>
            <el-date-picker
              v-model="filterDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 220px;"
              @change="handleFilterChange"
            />
          </div>
        </div>
      </div>

      <!-- 项目列表 -->
      <el-table :data="filteredProjects" v-loading="loading" stripe>
        <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="projectNumber" label="项目编号" width="150" />
        <el-table-column prop="projectType" label="项目类型" width="100" />
        <el-table-column prop="subjectCategory" label="学科分类" width="120" show-overflow-tooltip />
        <el-table-column prop="level" label="项目级别" width="100" />
        <el-table-column prop="sourceUnit" label="来源单位" width="150" show-overflow-tooltip />
        <el-table-column prop="totalFunding" label="经费总额" width="120">
          <template #default="{ row }">
            {{ row.totalFunding ? `${row.totalFunding}万元` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)" v-if="row.status === '已驳回'">
              编辑
            </el-button>
            <el-button type="text" style="color:#67c23a;" v-if="row.status === '已立项'" @click="startExecution(row)">
              开始执行
            </el-button>
            <el-button type="text" style="color:#e6a23c;" v-if="row.status === '执行中'" @click="handleFinish(row)">
              提交结题
            </el-button>
            <el-button type="text" style="color:#f56c6c;" @click="handleDelete(row)" v-if="row.status === '申报中' || row.status === '已驳回'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑科研项目对话框 -->
    <el-dialog
      v-model="showFormDialog"
      :title="editingProject ? '编辑科研项目' : '新建科研项目'"
      width="900px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        @submit.prevent
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h4>基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectNumber">
                <el-input v-model="formData.projectNumber" placeholder="请输入项目编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目类型" prop="projectType">
                <el-select v-model="formData.projectType" placeholder="请选择项目类型">
                  <el-option label="纵向" value="纵向" />
                  <el-option label="横向" value="横向" />
                  <el-option label="校级" value="校级" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="学科分类" prop="subjectCategory">
                <el-input v-model="formData.subjectCategory" placeholder="请输入学科分类" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目级别" prop="level">
                <el-select v-model="formData.level" placeholder="请选择项目级别">
                  <el-option label="校级" value="校级" />
                  <el-option label="市厅级" value="市厅级" />
                  <el-option label="省部级" value="省部级" />
                  <el-option label="国家级" value="国家级" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="来源单位" prop="sourceUnit">
                <el-input v-model="formData.sourceUnit" placeholder="请输入来源单位" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报日期" prop="applicationDate">
                <el-date-picker
                  v-model="formData.applicationDate"
                  type="date"
                  placeholder="请选择申报日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 项目时间 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                v-model="formData.startDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                @change="validateDateRange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                v-model="formData.endDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                @change="validateDateRange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 项目成员管理 -->
        <el-form-item label="项目成员">
          <div class="members-section">
            <el-table :data="formData.members" border size="small" style="margin-bottom: 16px;">
              <el-table-column prop="staffNo" label="工号" min-width="120">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.staffNo"
                    placeholder="请输入工号"
                    @blur="autoFillMemberInfo($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.name"
                    placeholder="姓名"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="department" label="部门" min-width="150">
                <template #default="{ row }">
                  <el-input
                    v-model="row.department"
                    placeholder="部门"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色" min-width="100">
                <template #default="{ row }">
                  <el-select v-model="row.role" placeholder="角色" style="width: 100%">
                    <el-option label="负责人" value="负责人" />
                    <el-option label="成员" value="成员" />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="text" @click="removeMember($index)" style="color: #f56c6c;">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" plain @click="addMember">
              <el-icon><Plus /></el-icon>
              添加成员
            </el-button>
          </div>
        </el-form-item>

        <!-- 经费预算 -->
        <el-form-item label="经费预算">
          <div class="funding-section">
            <el-table :data="formData.fundings" border size="small" style="margin-bottom: 16px;">
              <el-table-column prop="amount" label="金额(万元)" min-width="120">
                <template #default="{ row, $index }">
                  <el-input-number
                    v-model="row.amount"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入金额"
                    @change="validateFundingItem($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="source" label="经费来源" min-width="150">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.source"
                    placeholder="请输入经费来源"
                    @input="validateFundingItem($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="purpose" label="用途" min-width="150">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.purpose"
                    placeholder="请输入用途"
                    @input="validateFundingItem($index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="到账情况" min-width="120">
                <template #default="{ row }">
                  <el-select v-model="row.status" placeholder="选择到账情况" style="width: 100%">
                    <el-option label="未到账" value="未到账" />
                    <el-option label="部分到账" value="部分到账" />
                    <el-option label="全部到账" value="全部到账" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="text" @click="removeFunding($index)" style="color: #f56c6c;">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" plain @click="addFunding">
              <el-icon><Plus /></el-icon>
              添加经费项
            </el-button>
            <div class="funding-total" v-if="formData.fundings.length > 0">
              <span>经费总计：{{ getTotalFunding().toFixed(2) }} 万元</span>
            </div>
          </div>
        </el-form-item>

        <!-- 文件上传区域 -->
        <el-form-item label="相关附件">
          <div class="upload-section">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                drag
                :file-list="fileList"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :before-upload="beforeUpload"
                :auto-upload="false"
                multiple
                accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar"
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传申报书、立项书、结题报告等文档<br>
                  支持格式：PDF、DOC、DOCX、PPT、PPTX、XLS、XLSX、TXT、ZIP、RAR<br>
                  单个文件大小不超过 50MB，最多上传 10 个文件
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ editingProject ? '保存' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看项目详情对话框 -->
    <el-dialog
      v-model="showViewDialog"
      title="项目详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="view-dialog-content">
        <el-form :model="viewData" label-width="120px" class="view-form">
          <el-row :gutter="16">
            <el-col :span="24">
              <el-form-item label="项目名称">
                <el-input v-model="viewData.name" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="项目编号">
                <el-input v-model="viewData.projectNumber" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目类型">
                <el-input v-model="viewData.projectType" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="学科分类">
                <el-input v-model="viewData.subjectCategory" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目级别">
                <el-input v-model="viewData.level" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="来源单位">
                <el-input v-model="viewData.sourceUnit" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目状态">
                <el-tag :type="getStatusType(viewData.status)">{{ viewData.status }}</el-tag>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-input v-model="viewData.startDate" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-input v-model="viewData.endDate" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 项目成员 -->
          <el-form-item label="项目成员">
            <el-table :data="viewData.members" border size="small" v-if="viewData.members && viewData.members.length">
              <el-table-column prop="staffNo" label="工号" min-width="120" />
              <el-table-column prop="name" label="姓名" min-width="120" />
              <el-table-column prop="department" label="部门" min-width="150" />
              <el-table-column prop="role" label="角色" min-width="100" />

            </el-table>
            <div v-else class="empty-tip">暂无成员信息</div>
          </el-form-item>

          <!-- 经费预算 -->
          <el-form-item label="经费预算">
            <el-table :data="viewData.fundings" border size="small" v-if="viewData.fundings && viewData.fundings.length">
              <el-table-column prop="amount" label="金额(万元)" min-width="120">
                <template #default="{ row }">
                  {{ row.amount ? row.amount.toFixed(2) : '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="source" label="经费来源" min-width="150" />
              <el-table-column prop="purpose" label="用途" min-width="150" />
              <el-table-column prop="status" label="到账情况" min-width="120" />
            </el-table>
            <div v-if="viewData.fundings && viewData.fundings.length" class="funding-total">
              <span>经费总计：{{ getTotalViewFunding().toFixed(2) }} 万元</span>
            </div>
            <div v-else class="empty-tip">暂无经费信息</div>
          </el-form-item>

          <!-- 审核意见（如果存在） -->
          <el-form-item label="审核意见" v-if="viewData.reviewOpinion">
            <el-input v-model="viewData.reviewOpinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 结题审核意见（如果存在） -->
          <el-form-item label="结题审核意见" v-if="viewData.finishReviewOpinion">
            <el-input v-model="viewData.finishReviewOpinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 时间信息 -->
          <el-row :gutter="16" v-if="viewData.applicationDate || viewData.createdAt">
            <el-col :span="12" v-if="viewData.applicationDate">
              <el-form-item label="申报日期">
                <el-input v-model="viewData.applicationDate" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="viewData.createdAt">
              <el-form-item label="创建时间">
                <el-input :value="formatDateTime(viewData.createdAt)" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 项目描述 -->
          <el-form-item label="项目描述" v-if="viewData.description">
            <el-input v-model="viewData.description" type="textarea" :rows="3" readonly />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="showViewDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleEditFromView" v-if="viewData && (viewData.status === '申报中' || viewData.status === '已驳回')">
          编辑
        </el-button>
      </template>
    </el-dialog>

    <!-- 结题提交对话框 -->
    <el-dialog
      v-model="showFinishDialog"
      title="提交结题材料"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="finishFormRef"
        :model="finishFormData"
        :rules="finishFormRules"
        label-width="120px"
      >
        <el-form-item label="结题日期" prop="finishDate">
          <el-date-picker
            v-model="finishFormData.finishDate"
            type="date"
            placeholder="请选择结题日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结题形式" prop="finishType">
          <el-select v-model="finishFormData.finishType" placeholder="请选择结题形式">
            <el-option label="验收" value="验收" />
            <el-option label="结题报告" value="结题报告" />
            <el-option label="成果鉴定" value="成果鉴定" />
          </el-select>
        </el-form-item>
        <el-form-item label="结题等级" prop="finishLevel">
          <el-select v-model="finishFormData.finishLevel" placeholder="请选择结题等级">
            <el-option label="优秀" value="优秀" />
            <el-option label="良好" value="良好" />
            <el-option label="合格" value="合格" />
          </el-select>
        </el-form-item>
        <el-form-item label="结题成果" prop="finishResults">
          <el-input
            v-model="finishFormData.finishResults"
            type="textarea"
            :rows="4"
            placeholder="请详细描述项目成果（论文、专利、软件著作权、报告等）"
          />
        </el-form-item>
        <el-form-item label="成果列表" prop="resultsList">
          <el-input
            v-model="finishFormData.resultsList"
            type="textarea"
            :rows="3"
            placeholder="请列出具体的成果清单"
          />
        </el-form-item>
        
        <!-- 结题附件上传 -->
        <el-form-item label="结题附件">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :file-list="finishFileList"
            :before-upload="beforeFinishUpload"
            :on-change="handleFinishFileChange"
            :on-remove="handleFinishFileRemove"
            multiple
            accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传结题报告、研究成果等材料<br>
                支持格式：PDF、DOC、DOCX、PPT、PPTX、XLS、XLSX、TXT、ZIP、RAR<br>
                单个文件大小不超过 50MB，最多上传 10 个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showFinishDialog = false">取消</el-button>
          <el-button type="primary" @click="handleFinishSubmit" :loading="submitting">
            提交结题
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Delete, UploadFilled, Download } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getMyResearchProjects,
  createResearchProject,
  updateResearchProject,
  deleteResearchProject,
  getResearchProjectById,
  startProjectExecution,
  submitResearchFinish
} from '@/api/researchProject'
import http from '@/utils/request'
import axios from 'axios'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const projects = ref([])
const showFormDialog = ref(false)
const showViewDialog = ref(false)
const showFinishDialog = ref(false)
const editingProject = ref(null)

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')
const filterType = ref('')
const filterLevel = ref('')
const filterFundingMin = ref(null)
const filterFundingMax = ref(null)
const filterDateRange = ref(null)

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 表单数据
const formRef = ref()
const uploadRef = ref()
const fileList = ref([])
const finishFileList = ref([])
const formData = reactive({
  name: '',
  projectNumber: '',
  projectType: '',
  subjectCategory: '',
  level: '',
  sourceUnit: '',
  applicationDate: null,
  startDate: null,
  endDate: null,
  totalFunding: null,
  fundingSource: '',
  fundingStatus: '',
  description: '',
  members: [{
    name: '',
    staffNo: '',
    department: '',
    role: '负责人',
    userId: null
  }],
  fundings: []
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  projectType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择项目级别', trigger: 'change' }],
  applicationDate: [{ required: true, message: '请选择申报日期', trigger: 'change' }]
}

// 查看详情数据
const viewData = reactive({
  name: '',
  projectNumber: '',
  projectType: '',
  subjectCategory: '',
  level: '',
  sourceUnit: '',
  totalFunding: null,
  fundingSource: '',
  fundingStatus: '',
  status: '',
  applicationDate: null,
  startDate: null,
  endDate: null,
  createdAt: null,
  description: '',
  members: [],
  reviewOpinion: '',
  finishReviewOpinion: ''
})

// 结题表单数据
const finishFormRef = ref()
const finishFormData = reactive({
  finishDate: null,
  finishType: '',
  finishLevel: '',
  finishResults: '',
  resultsList: ''
})

// 结题表单验证规则
const finishFormRules = {
  finishDate: [{ required: true, message: '请选择结题日期', trigger: 'change' }],
  finishType: [{ required: true, message: '请选择结题形式', trigger: 'change' }],
  finishLevel: [{ required: true, message: '请选择结题等级', trigger: 'change' }],
  finishResults: [{ required: true, message: '请输入结题成果', trigger: 'blur' }]
}

// 计算属性 - 过滤后的项目列表
const filteredProjects = computed(() => {
  let filtered = projects.value

  // 项目名称搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(p => 
      p.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  // 项目状态筛选
  if (filterStatus.value) {
    filtered = filtered.filter(p => p.status === filterStatus.value)
  }
  
  // 项目类型筛选
  if (filterType.value) {
    filtered = filtered.filter(p => p.projectType === filterType.value)
  }
  
  // 项目级别筛选
  if (filterLevel.value) {
    filtered = filtered.filter(p => p.level === filterLevel.value)
  }
  
  // 经费区间筛选
  if (filterFundingMin.value !== null || filterFundingMax.value !== null) {
    filtered = filtered.filter(p => {
      const funding = parseFloat(p.totalFunding) || 0
      const min = filterFundingMin.value || 0
      const max = filterFundingMax.value || Infinity
      return funding >= min && funding <= max
    })
  }
  

  
  // 申报时间区间筛选
  if (filterDateRange.value && filterDateRange.value.length === 2) {
    const [startDate, endDate] = filterDateRange.value
    filtered = filtered.filter(p => {
      if (!p.applicationDate) return false
      const projectDate = new Date(p.applicationDate)
      return projectDate >= startDate && projectDate <= endDate
    })
  }

  pagination.total = filtered.length
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  return filtered.slice(start, end)
})

// 获取项目列表
const fetchProjects = async () => {
  try {
    loading.value = true
    const userId = userStore.userInfo?.id
    if (!userId) {
      ElMessage.error('用户信息获取失败')
      return
    }
    const response = await getMyResearchProjects(userId)
    projects.value = Array.isArray(response) ? response : (response?.data || [])
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 基础方法
const handleView = async (project) => {
  try {
    const response = await getResearchProjectById(project.id)
    const detail = response?.data || response
    
    const proj = detail.project || detail
    Object.assign(viewData, {
      name: proj.name,
      projectNumber: proj.projectNumber,
      projectType: proj.projectType,
      subjectCategory: proj.subjectCategory,
      level: proj.level,
      sourceUnit: proj.sourceUnit,
      totalFunding: detail.totalFunding || proj.totalFunding,
      fundingSource: proj.fundingSource,
      fundingStatus: proj.fundingStatus,
      status: proj.status,
      applicationDate: proj.applicationDate,
      startDate: proj.startDate,
      endDate: proj.endDate,
      createdAt: proj.createdAt,
      description: proj.description,
      members: detail.members || [],
      fundings: detail.fundings || [],
      attachments: detail.attachments || [],
      reviewOpinion: proj.reviewOpinion,
      finishReviewOpinion: proj.finishReviewOpinion
    })
    
    showViewDialog.value = true
  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  }
}

const handleEdit = async (project) => {
  try {
    const response = await getResearchProjectById(project.id)
    const detail = response?.data || response
    
    editingProject.value = project
    
    const proj = detail.project || detail
    Object.assign(formData, {
      name: proj.name,
      projectNumber: proj.projectNumber,
      projectType: proj.projectType,
      subjectCategory: proj.subjectCategory,
      level: proj.level,
      sourceUnit: proj.sourceUnit,
      applicationDate: proj.applicationDate ? proj.applicationDate.split('T')[0] : null,
      startDate: proj.startDate ? proj.startDate.split('T')[0] : null,
      endDate: proj.endDate ? proj.endDate.split('T')[0] : null,
      totalFunding: detail.totalFunding || proj.totalFunding,
      fundingSource: proj.fundingSource,
      fundingStatus: proj.fundingStatus,
      description: proj.description,
      members: detail.members && detail.members.length > 0 ? detail.members.map(m => ({
        name: m.name || '',
        staffNo: m.staffNo || '',
        department: m.department || '',
        role: m.role || '成员',
        userId: m.userId || null
      })) : [{
        name: '',
        staffNo: '',
        department: '',
        role: '负责人',
        userId: null
      }],
      fundings: detail.fundings || []
    })
    
    // 设置文件列表
    fileList.value = detail.attachments ? detail.attachments.map(att => ({
      name: att.fileName,
      url: att.fileUrl,
      uid: att.id
    })) : []
    
    showFormDialog.value = true
  } catch (error) {
    console.error('获取项目详情失败:', error)
    ElMessage.error('获取项目详情失败')
  }
}

const handleDelete = async (project) => {
  try {
    await ElMessageBox.confirm(`确定删除项目"${project.name}"吗？`, '删除确认', {
      type: 'warning'
    })
    await deleteResearchProject(project.id)
    ElMessage.success('项目删除成功')
    fetchProjects()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 开始执行项目
const startExecution = async (project) => {
  try {
    await ElMessageBox.confirm(`确定开始执行项目"${project.name}"吗？`, '开始执行', {
      type: 'info'
    })
    await startProjectExecution(project.id)
    ElMessage.success('项目已开始执行')
    fetchProjects()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const handleFinish = (project) => {
  editingProject.value = project
  
  // 重置结题表单
  Object.assign(finishFormData, {
    finishDate: null,
    finishType: '',
    finishLevel: '',
    finishResults: '',
    resultsList: ''
  })
  
  // 重置结题文件列表
  finishFileList.value = []
  
  showFinishDialog.value = true
}

// 工具函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  try {
    return new Date(dateTimeStr).toLocaleString('zh-CN')
  } catch {
    return '-'
  }
}

const getStatusType = (status) => {
  const types = {
    '申报中': 'warning',
    '已立项': 'success',
    '执行中': 'primary',
    '结题审核中': 'info',
    '已结题': 'success',
    '已驳回': 'danger'
  }
  return types[status] || 'info'
}

// 筛选
const handleFilterChange = () => {
  pagination.page = 1
}

// 分页
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
}

const handleCurrentChange = (page) => {
  pagination.page = page
}

// 表单处理方法
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    projectNumber: '',
    projectType: '',
    subjectCategory: '',
    level: '',
    sourceUnit: '',
    applicationDate: null,
    startDate: null,
    endDate: null,
    totalFunding: null,
    fundingSource: '',
    fundingStatus: '',
    description: '',
    members: [{
      name: '',
      staffNo: '',
      department: '',
      role: '负责人',
      userId: null
    }],
    fundings: []
  })
  fileList.value = []
  editingProject.value = null
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const handleDialogClose = () => {
  resetForm()
  showFormDialog.value = false
}

// 成员管理方法
const addMember = () => {
  formData.members.push({
    name: '',
    staffNo: '',
    department: '',
    role: '成员',
    userId: null
  })
}

const removeMember = (index) => {
  if (formData.members.length > 1) {
    formData.members.splice(index, 1)
  }
}

const autoFillMemberInfo = async (index) => {
  const member = formData.members[index]
  const staffNo = member.staffNo?.trim()
  if (!staffNo) return
  
  try {
    // 使用axios直接发送请求，确保携带认证信息
    const token = userStore.token
    const resp = await axios.get('/api/research-projects/check', { 
      params: { staffNo },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    const data = resp?.data || resp
    if (data && data.exist) {
      member.name = data.name
      member.department = data.department
      member.userId = data.userId
      ElMessage.success('已自动填充成员信息')
    } else {
      ElMessage.warning('未找到该工号对应的人员，请手动填写')
    }
  } catch (e) {
    console.error('工号查询失败:', e)
    if (e.response?.status === 401) {
      ElMessage.error('认证失败，请重新登录')
    } else if (e.response?.status === 403) {
      ElMessage.error('权限不足，无法查询用户信息')
    } else {
      ElMessage.warning('查询工号失败，请手动填写')
    }
  }
}

// 经费管理方法
const addFunding = () => {
  formData.fundings.push({
    amount: null,
    source: '',
    purpose: '',
    status: '未到账'
  })
}

const removeFunding = (index) => {
  formData.fundings.splice(index, 1)
  ElMessage.success('经费项删除成功')
}

const validateFundingItem = (index) => {
  const funding = formData.fundings[index]
  if (funding.amount !== null && funding.amount < 0) {
    ElMessage.warning('经费金额不能为负数')
    funding.amount = 0
  }
}

const getTotalFunding = () => {
  return formData.fundings.reduce((total, funding) => {
    return total + (funding.amount || 0)
  }, 0)
}

// 日期验证方法
const validateDateRange = () => {
  if (formData.startDate && formData.endDate) {
    const startDate = new Date(formData.startDate)
    const endDate = new Date(formData.endDate)
    if (startDate >= endDate) {
      ElMessage.warning('开始时间应早于结束时间，请重新选择')
      formData.endDate = null
    }
  }
}

// 文件上传相关方法
const beforeUpload = (file) => {
  const isValidSize = file.size <= 50 * 1024 * 1024 // 50MB
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  const fileCount = fileList.value.length
  if (fileCount >= 10) {
    ElMessage.error('最多只能上传 10 个文件!')
    return false
  }

  return false // 阻止自动上传
}

const handleFileChange = (file, newFileList) => {
  fileList.value = newFileList
}

const handleFileRemove = async (file, newFileList) => {
  fileList.value = newFileList
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    // 构建数据对象
    const projectData = {
      name: formData.name,
      projectNumber: formData.projectNumber || '',
      projectType: formData.projectType || '',
      subjectCategory: formData.subjectCategory || '',
      level: formData.level || '',
      sourceUnit: formData.sourceUnit || '',
      applicationDate: formData.applicationDate || '',
      startDate: formData.startDate || '',
      endDate: formData.endDate || '',
      totalFunding: formData.totalFunding || 0,
      fundingSource: formData.fundingSource || '',
      fundingStatus: formData.fundingStatus || '',
      description: formData.description || '',
      members: formData.members.map(m => ({
        name: m.name,
        staffNo: m.staffNo,
        department: m.department,
        role: m.role,
        userId: m.userId
      })),
      fundings: formData.fundings.map(f => ({
        amount: f.amount,
        source: f.source,
        purpose: f.purpose,
        status: f.status
      }))
    }
    
    // 构建FormData，按照后端期望的格式
    const formDataToSubmit = new FormData()
    formDataToSubmit.append('data', JSON.stringify(projectData))
    
    // 添加文件
    fileList.value.forEach(file => {
      if (file.raw) {
        formDataToSubmit.append('files', file.raw)
      }
    })
    
    if (editingProject.value) {
      await updateResearchProject(editingProject.value.id, formDataToSubmit)
      ElMessage.success('项目更新成功')
    } else {
      await createResearchProject(formDataToSubmit)
      ElMessage.success('项目创建成功')
    }
    
    handleDialogClose()
    fetchProjects()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

const handleFinishSubmit = async () => {
  if (!finishFormRef.value) return
  
  try {
    const valid = await finishFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    const submitData = {
      ...finishFormData,
      finishDate: finishFormData.finishDate.toISOString().split('T')[0]
    }
    
    // 构建FormData格式
    const formDataToSubmit = new FormData()
    formDataToSubmit.append('data', JSON.stringify(submitData))
    
    // 添加结题附件文件
    if (finishFileList.value && finishFileList.value.length > 0) {
      finishFileList.value.forEach(file => {
        if (file.raw) {
          formDataToSubmit.append('files', file.raw)
        }
      })
    }
    
    await submitResearchFinish(editingProject.value.id, formDataToSubmit)
    ElMessage.success('结题材料提交成功')
    
    showFinishDialog.value = false
    fetchProjects()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 结题文件上传相关方法
const beforeFinishUpload = (file) => {
  const isValidSize = file.size <= 50 * 1024 * 1024 // 50MB
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  const fileCount = finishFileList.value.length
  if (fileCount >= 10) {
    ElMessage.error('最多只能上传 10 个文件!')
    return false
  }

  return false // 阻止自动上传
}

const handleFinishFileChange = (file, newFileList) => {
  finishFileList.value = newFileList
}

const handleFinishFileRemove = (file, newFileList) => {
  finishFileList.value = newFileList
}

// 添加格式化日期的工具函数
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  try {
    return new Date(dateStr).toLocaleDateString('zh-CN')
  } catch {
    return '-'
  }
}

// 计算查看界面的经费总额
const getTotalViewFunding = () => {
  if (!viewData.fundings || !Array.isArray(viewData.fundings)) return 0
  return viewData.fundings.reduce((total, funding) => {
    return total + (parseFloat(funding.amount) || 0)
  }, 0)
}

// 下载文件
const downloadFile = (attachment) => {
  // 这里调用下载API
  console.log('下载文件:', attachment)
  // downloadResearchAttachment(attachment.id, attachment.fileName)
}

// 从查看界面进入编辑
const handleEditFromView = () => {
  showViewDialog.value = false
  handleEdit(viewData)
}

// 导出数据
const exportData = async () => {
  const { exportData: exportUtil } = await import('@/utils/exportUtils')
  
  const filters = {
    search: searchKeyword.value,
    status: filterStatus.value,
    type: filterType.value,
    level: filterLevel.value
  }
  
  await exportUtil('research-projects', filters, '科研项目列表.xlsx')
}

// 挂载时获取数据
onMounted(() => {
  fetchProjects()
})
</script>

<style scoped>
.research-projects {
  max-width: 1400px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
}

.filter-bar {
  margin-bottom: 16px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.funding-range {
  display: flex;
  align-items: center;
  gap: 4px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-bar {
    flex-wrap: wrap;
    gap: 8px;
  }
}

.form-section {
  margin-bottom: 24px;
}

.form-section h4 {
  margin: 0 0 16px 0;
  color: #606266;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.member-item {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}

.members-section {
  width: 100%;
}

.funding-section {
  width: 100%;
}

.funding-total {
  margin-top: 12px;
  text-align: right;
  font-weight: bold;
  color: #409eff;
}

.upload-section {
  width: 100%;
}

.upload-demo {
  width: 100%;
}

.el-upload__tip {
  line-height: 1.5;
  color: #999;
  font-size: 12px;
}

.view-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.view-form .el-form-item {
  margin-bottom: 16px;
}

.empty-tip {
  color: #999;
  font-size: 14px;
  text-align: center;
  padding: 20px 0;
}

.funding-total {
  margin-top: 12px;
  text-align: right;
  font-weight: bold;
  color: #409eff;
}
</style>